from machine import I2C,Pin
from ssd1306 import SSD1306_I2C
import utime

i2c = I2C(scl = Pin(16), sda=Pin(17))
oled = SSD1306_I2C(128, 64, i2c)

button_down = Pin(18, Pin.IN, Pin.PULL_UP)
button_click = Pin(13, Pin.IN, Pin.PULL_UP)

#方便的菜单
class Menu:
    nowRectX = 0
    nowSlide = 0
    Slide = 0
    lastSlideTime = utime.ticks_ms()

    item_cnt = 0
    items = []
    
    def __init__(self, items):
        self.nowRectX = 0
        self.nowSlide = 0
        self.Slide = 0
        self.lastSlideTime = utime.ticks_ms()
        self.item_cnt = 0
        self.items = []

        self.item_cnt = len(items)
        for item in items: self.items.append(item)

    #== 这两个函数不需要外部调用
    def Lerp(self, x, tar_x,t): # 线性插值
        return (tar_x-x)/t

    def printMainMenuFrame(self, slide, nowRectX, item_cnt, items): #打印
        oled.fill(0)
        for i in range(item_cnt):
            pos_y = 5 + i*16 + -16*slide
            oled.text(items[i],5,int(pos_y))
        
        oled.draw_rect(2,2,int(nowRectX),8+6,1)
        oled.show()
    #====

    # 开启菜单以供选择选项
    def runMenu(self):
        self.lastSlideTime = utime.ticks_ms()
        while True:
            self.nowSlide += self.Lerp(self.nowSlide, self.Slide, 2.5)
            self.nowRectX += self.Lerp(self.nowRectX,len(self.items[int(self.Slide)])*8+6,2.5)
            self.printMainMenuFrame(self.nowSlide, self.nowRectX, self.item_cnt, self.items)
            
            print(button_down.value())
            if(button_down.value() == 0 and utime.ticks_ms()-self.lastSlideTime > 160):
                self.Slide += 1
                print("Slide: "+str(self.Slide))
                self.lastSlideTime = utime.ticks_ms()
                if(self.Slide >= self.item_cnt): self.Slide = 0

            if(button_click.value() == 0):
                return self.Slide